package com.example.mvc.controller;

import com.example.mvc.bean.User;
import com.example.mvc.service.UserService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet  extends HttpServlet {
    private UserService userService = new UserService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取到用户输入的用户名和 密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //通过用户输入的用户名和密码查询用户表
        User loginUser = userService.login(username, password);

        if (loginUser!=null){//登录成功

            //判断用户是否勾选记住我
            String remember = req.getParameter("remember");
            if("1".equals(remember)){
                //勾选了，发送Cookie

                //1. 创建Cookie对象
                Cookie c_username = new Cookie("username",username);
                Cookie c_password = new Cookie("password",password);
                // 设置Cookie的存活时间
                c_username.setMaxAge( 60 * 60 * 24 * 7);
                c_password.setMaxAge( 60 * 60 * 24 * 7);
                //2. 发送
                resp.addCookie(c_username);
                resp.addCookie(c_password);
            }
            //登录成功把用户存入session
            HttpSession session = req.getSession();
            session.setAttribute("user",loginUser);
            //工程的路径
            String contextPath = req.getContextPath();
            //登录成功，跳转到主界面进到系统
            resp.sendRedirect(contextPath+"/selectAllServlet");
        }else {//登录失败
            //登录失败，提示用户名或密码错误，调到登录界面
            req.setAttribute("login_msg","用户名或密码错误");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }




    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
}
